/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.icanci.timedtask.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.icanci.basic.commonutils.R;
import cn.icanci.timedtask.client.EmailServiceClient;
import cn.icanci.timedtask.client.OrderServiceClient;
import cn.icanci.timedtask.client.dto.OrderInfoDTO;
import cn.icanci.timedtask.service.ScheduledService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;

/**
 * @author icanci
 * @date Created in 2021/04/28 11:52
 * @version 1.0
 */
@Service
@Slf4j
public class ScheduledServiceImpl implements ScheduledService {

    @Resource
    private OrderServiceClient        orderServiceClient;
    @Resource
    private EmailServiceClient        emailServiceClient;
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 定时任务，定时发送验证码和短信，提示用户下单
     * 0 0/3 * * * ? * 每3分钟执行一次
     */
    @Transactional(rollbackFor = Exception.class)
    @Scheduled(cron = "0 0/1 * * * ?")
    @Override
    public void book() {
        R r = orderServiceClient.queryManyRowByAdmin();
        List<LinkedHashMap> list = (List<LinkedHashMap>) r.getData().get("orderInfos");
        if (CollectionUtil.isEmpty(list)) {
            log.warn("订单查询结果为null");
            return;
        }
        ArrayList<OrderInfoDTO> orderInfoDTOS = Lists.newArrayList();
        for (LinkedHashMap map : list) {
            OrderInfoDTO orderInfoDTO = objectMapper.convertValue(map, OrderInfoDTO.class);
            orderInfoDTOS.add(orderInfoDTO);
        }
        if (CollectionUtil.isNotEmpty(orderInfoDTOS)) {
            for (OrderInfoDTO infoDTO : orderInfoDTOS) {
                // 获取状态
                if (infoDTO.getOrderStatus() != 1) {
                    continue;
                }
                Date createTime = infoDTO.getCreateTime();
                long between = DateUtil.between(createTime, new Date(), DateUnit.MINUTE);
                if (between > 15) {
                    // 订单超时
                    // 更改订单的状态
                    orderServiceClient.cancelOrder(infoDTO.getOrderId());
                    // 发送邮件
                    emailServiceClient.cancelOrderEmail(infoDTO.getEmailAddress(), infoDTO.getOrderSerialNo(), infoDTO.getStartCity(), infoDTO.getArriveCity());
                    log.info("执行完毕...");
                }
            }
            log.info("数据遍历完毕...，一分钟之后开始下一轮...");
        }
    }
}
